//
//  Encryption.m
//  Pthread
//
//  Created by Yanyan Jiang on 2025/3/7.
//  Copyright © 2025 Yanyan Jiang. All rights reserved.
//

#import "NSData+Encryption.h"
#import <CommonCrypto/CommonCrypto.h>
#import "AESUtil.h"



@implementation NSData (Encryption)


- (NSData *)aes256EncryptWithKey:(NSData *)key iv:(NSData *)iv {
    // 将密钥和 IV 转换为 NSData
//    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
//    NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *keyData = key;
    NSData *ivData = iv;
    
    // 检查密钥和 IV 的长度
    if (keyData.length != kCCKeySizeAES256) {
        NSLog(@"密钥长度必须为 32 字节（256位）");
        return nil;
    }
    if (ivData.length != kCCBlockSizeAES128) {
        NSLog(@"IV 长度必须为 16 字节（128位）");
        return nil;
    }
    
    // 准备加密输出缓冲区
    size_t bufferSize = self.length + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    
    // 执行 AES 加密
    CCCryptorStatus cryptStatus = CCCrypt(
        kCCEncrypt,                     // 操作类型：加密
        kCCAlgorithmAES,                // 算法：AES
        kCCOptionPKCS7Padding,          // 填充方式：PKCS7
        keyData.bytes,                  // 密钥字节
        kCCKeySizeAES256,               // 密钥长度
        ivData.bytes,                   // IV 字节
        self.bytes,                     // 输入数据
        self.length,                    // 输入数据长度
        buffer,                        // 输出缓冲区
        bufferSize,                     // 输出缓冲区大小
        &numBytesEncrypted             // 加密后数据实际长度
    );
    
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    
    free(buffer);
    return nil;
}

- (NSData *)aes256DecryptWithKey:(NSData *)key iv:(NSData *)iv {
    // 类似加密过程，操作类型改为 kCCDecrypt
//    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
//    NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *keyData = key;
    NSData *ivData = iv;
    
    if (keyData.length != kCCKeySizeAES256 || ivData.length != kCCBlockSizeAES128) {
        return nil;
    }
    
    size_t bufferSize = self.length + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(
        kCCDecrypt,
        kCCAlgorithmAES,
        kCCOptionPKCS7Padding,
        keyData.bytes,
        kCCKeySizeAES256,
        ivData.bytes,
        self.bytes,
        self.length,
        buffer,
        bufferSize,
        &numBytesDecrypted
    );
    
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    
    free(buffer);
    return nil;
}

@end
